package com.ysynzehao.service.impl;

import com.ysynzehao.bean.User;
import com.ysynzehao.service.UserService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * niuzehao
 * 2018/11/30 18:06.
 */
@Service
public class UserServiceImpl implements UserService {

    private Map<String, User> userMap = new HashMap<>();

    @Override
    public User saveUser(User user) {
        userMap.put(user.getUserId(), user);
        return user;
    }

    /**
     * unless = "#result == null" 如果返回值为null,不缓存结果
     * @param userId
     * @return
     */
    @Override
    @Cacheable(value = "user_", key = "#userId", unless = "#result == null")
    public User getUser(String userId) {
        return userMap.get(userId);
    }

    @Override
    @CachePut(value = "user_", key = "#user.userId")
    public User updateUser(User user) {
        userMap.put(user.getUserId(), user);
        return user;
    }

    @Override
    @CacheEvict(value = "user_", key = "#userId")
    public void deleteUser(String userId) {
        userMap.remove(userId);
    }
}
